<template>
  <customContainer ref="customContainerRef" :config="config" />
  <!-- 新增-修改发货人信息弹出框 -->
  <el-dialog
    v-model="open"
    :title="title"
    :close-on-click-modal="false"
    append-to-body
  >
    <el-form
      ref="editform"
      inline
      label-width="95px"
      :rules="rules"
      :model="form"
    >
      <el-form-item label="费用类型" prop="costTypeId">
        <el-select v-model="form.costTypeId" filterable>
          <el-option
            v-for="dict in dicts[DictDirection.费用名称]"
            :key="dict.id"
            :label="dict.feeName"
            :value="dict.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="收取方式" prop="costTypeWay">
        <el-select v-model="form.costTypeWay" filterable>
          <el-option
            v-for="dict in dicts[DictDirection.费用收取方式]"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="form.costTypeWay == '1'" label="开始" prop="staerWeight">
        <el-input-number
          v-model="form.staerWeight"
          controls-position="right"
          clearable
        ></el-input-number>
      </el-form-item>
      <el-form-item v-if="form.costTypeWay == '1'" label="结束" prop="endWeight">
        <el-input-number
          v-model="form.endWeight"
          controls-position="right"
          clearable
        ></el-input-number>
      </el-form-item>
      <el-form-item label="费用金额" prop="cost">
        <el-input-number
          v-model="form.cost"
          controls-position="right"
          clearable
        ></el-input-number>
      </el-form-item>
      <el-form-item label="计费方法" prop="billingWay">
        <el-select v-model="form.billingWay" filterable>
          <el-option
            v-for="dict in dicts[DictDirection.计费方式]"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remakr">
        <el-input
          v-model="form.remakr"
          type="textarea"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div>
        <el-button type="primary" @click="submitServiceForm">确定</el-button>
        <el-button @click="cancelService">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import {
  Delete,
  Plus,
  Edit,
} from '@element-plus/icons-vue'
import { ref, getCurrentInstance, defineAsyncComponent, computed, defineProps, watch } from 'vue'
import { ElMessage, ElMessageBox, ElButton } from 'element-plus'
import { getSaleCostList, addSaleCost, getDetail, updateSaleCost, delSaleCost } from '@/api/BusinessConfig/salesChannelExpenses'
import userDicts, { DictDirection } from '@/store/modules/dicts'

const dicts = userDicts()
dicts.setDicts(DictDirection.费用名称)
dicts.setDicts(DictDirection.费用收取方式)
dicts.setDicts(DictDirection.计费方式)
const props = defineProps({
  // eslint-disable-next-line vue/require-default-prop
  productId: {
    type: Number,
  },
  fatherOpen: {
    type: Boolean,
  },
})
let // 查询参数
  queryParams = ref({
    pageSize: 10,
    pageNum: 1,
    id: undefined,
  }),
  // 选中数组
  ids = [],
  // 非单个禁用
  single = ref(true),
  // 非多个禁用
  multiple = ref(true),
  customContainerRef = ref(null),
  // 新增-修改弹出框
  open = ref(false),
  // 新增-修改标题
  title = ref(undefined),
  // 规则
  rules = {
    staerWeight: [
      {
        required: true,
        message: '开始需要输入',
        trigger: ['blur'],
      },
    ],
    endWeight: [
      {
        required: true,
        message: '结束需要输入',
        trigger: ['blur'],
      },
    ],
    cost: [
      {
        required: true,
        message: '费用金额需要输入',
        trigger: ['blur'],
      },
    ],
    serviceChannelId: [
      {
        required: true,
        message: '服务渠道需要输入',
        trigger: ['blur'],
      },
    ],
  },
  form = ref({
    id: undefined,
    costTypeId: undefined,
    costTypeWay: undefined,
    staerWeight: undefined,
    endWeight: undefined,
    cost: undefined,
    billingWay: undefined,
    remakr: undefined,
    serviceChannelId: undefined,
  }),
  editform = ref(null),
  {
    proxy,

  }:{
    proxy:any
 
  } = getCurrentInstance()
// 查询
const handleQuery = () => {
  queryParams.value.pageNum = 1
  customContainerRef.value.getList()
}
// 多选框选中数据
const handleSelectionChange = (rows: { [key: string]: any }[]) => {
  const rowsList = JSON.parse(JSON.stringify(rows))
  ids = rowsList.map((item) => item.id)
  single.value = rowsList.length != 1
  multiple.value = !rowsList.length
}
/** 新增按钮操作 */
const handleAdd = () => {
  open.value = true
  title.value = '新建收费数据'
}
// 重置新增修改表单
const reset = () => {
  form.value = {
    id: undefined,
    costTypeId: undefined,
    costTypeWay: undefined,
    staerWeight: undefined,
    endWeight: undefined,
    cost: undefined,
    billingWay: undefined,
    remakr: undefined,
    serviceChannelId: undefined,
  }
  proxy.$resetForm(editform.value)
}
// 确定新增-修改服务渠道
const submitServiceForm = () => {
  proxy.$validateForm(editform.value, async () => {
    form.value.serviceChannelId = props.productId
    if (form.value.id != undefined) {
      updateSaleCost(form.value).then(res => {
        if (res.code == 200) {
          ElMessage.success('修改成功')
          handleQuery()
          reset()
          open.value = false
        }
      })
    } else {
      addSaleCost(form.value).then(res => {
        if (res.code == 200) {
          ElMessage.success('修改成功')
          handleQuery()
          reset()
          open.value = false
        }
      })
    }  
  })
}
// 取消新增-修改服务渠道
const cancelService = () => {
  reset()
  open.value = false
}
// 修改费用管理
const handleUpdate = (row:{[key:string]:any}) => {
  const id = (row && row.id) || ids[0]
  getDetail(id).then(res => {
    if (res.code == 200) {
      form.value = res.data
      open.value = true
      title.value = '修改服务渠道'
    }
  })
}
/** 删除按钮操作 */
const handleDelete = (row: { [key: string]: any }) => {
  const id = row.id || ids
  ElMessageBox.confirm(
    `"是否确认删除用户编号为"${ id }"的数据项?"`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
  .then(() => delSaleCost(id))
  .then((res) => {
    if (res.code === 200) {
      handleQuery()
      ElMessage.success('删除成功')
    } else {
      ElMessage.error(res.msg)
    }
  })
  .catch((error) => {
    if (error == 'cancel') {
      ElMessage.error(error)
    }
  })
}
const config = computed(() => ({
  query: {
    fields: [
    ],
    queryParams: queryParams.value,
  },
  btns: [
    {
      title: '新增',
      icon: Plus,
      onClick: handleAdd,
    },
    {
      title: '编辑',
      icon: Edit,
      disabled: single.value,
      onClick: handleUpdate,
      type: 'success',
    },
    {
      title: '删除',
      icon: Delete,
      onClick: handleDelete,
      type: 'danger',
    },
  ],
  table: {
    columns: [
      { type: 'selection', width: '55', align: 'center' },
      {
        label: '费用类型',
        prop: 'costTypeId',
        align: 'center',
        width: '90',
        autoFormatter: {
          dict: DictDirection.费用名称,
          rowKey: 'costTypeId',
        },
      },
      {
        label: '费用收取方式',
        prop: 'costTypeWay',
        align: 'center',
        width: '90',
        autoFormatter: {
          dict: DictDirection.费用收取方式,
          rowKey: 'costTypeWay',
        },
      },
      {
        label: '计费方式',
        prop: 'billingWay',
        align: 'center',
        width: '90',
        autoFormatter: {
          dict: DictDirection.计费方式,
          rowKey: 'billingWay',
        },
      },
      {
        label: '开始',
        prop: 'staerWeight',
        align: 'center',
        width: '90',
      },
      {
        label: '结束',
        prop: 'endWeight',
        align: 'center',
        width: '90',
      },
      {
        label: '费用金额',
        prop: 'cost',
        align: 'center',
        width: '90',    
      },
      {
        label: '备注',
        prop: 'remakr',
        align: 'center',
        width: '90',
      },
      {
        label: '操作',
        align: 'center',
        showOverflowTooltip: false,
        className: 'custormFixedCol',
        width: '200',
        render: (h, params) => {
          const buttons = [
            {
              title: '编辑',
              icon: Edit,
              clickFun: handleUpdate,
            },
            {
              title: '删除',
              icon: Delete,
              clickFun: handleDelete,
              directive: [['hasPermi', ['system:channel:remove']]],
             
            },
          ]
          return buttons.map((el) => h(
            ElButton,
            {
              text: true,
              type: 'primary',
              icon: el.icon,
              onClick: () => {
                el.clickFun(params.row)
              },
            },
            {
              default: () => el.title,
            },
          ))
        },
      },
    ],
    event: {
      onSelectionChange: (rows) => {
        handleSelectionChange(rows)
      },
    },
  },
  api: getSaleCostList,
  requestTrans: (q) => {
    q.id = props.productId
    queryParams.value = q
    return q
  },
}))

</script>
